package com.whc.pay.listener;

import com.whc.api.dto.PayApplyDTO;
import com.whc.pay.service.IPayOrderService;
import com.whc.pay.service.impl.PayOrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Component
@Slf4j
public class RabbitMqListener {
    @Autowired
    private IPayOrderService payOrderService;

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(String msg) throws InterruptedException {
        System.out.println("spring 消费者接收到消息：【" + msg + "】");
    }


    @Transactional
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("ordersTopic.queue"),
            exchange = @Exchange(name = "orders.topic",type = ExchangeTypes.TOPIC),
            key="#.orders"
    ))
    public void listenOrderQueueMessage(PayApplyDTO payApplyDTO)throws InterruptedException{
        try {
            log.info("消费者1接受到添加订单消息，开始生成支付单");
            payOrderService.addPay(payApplyDTO);
//            int a=1/0;
        }catch (Exception e){
            log.info("处理失败回滚事务");
            throw new RuntimeException("故意的");
        }
    }

    @Transactional
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("ordersTopic.queue"),
            exchange = @Exchange(name = "orders.topic",type = ExchangeTypes.TOPIC),
            key="#.orders"
    ))
    public void listenOrderQueueMessage2(PayApplyDTO payApplyDTO)throws InterruptedException{
        try {
            log.info("消费者2接受到添加订单消息，开始生成支付单");
            payOrderService.addPay(payApplyDTO);
        }catch (Exception e){
            log.info("处理失败回滚事务");
            throw new RuntimeException("故意的");
        }
    }
}
